package com.base.component.ai.platform.core.utils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

import org.springframework.http.HttpStatus;

import com.gitee.magic.core.exception.ApplicationException;

public class Utils {
	
	public static void streamConsumer200(HttpURLConnection connection, Consumer<String> frameConsumer) {
		streamConsumer(connection,Arrays.asList(HttpStatus.OK.value()),frameConsumer);
	}
	
	public static void streamConsumer200And201(HttpURLConnection connection, Consumer<String> frameConsumer) {
		streamConsumer(connection,Arrays.asList(HttpStatus.OK.value(),HttpStatus.CREATED.value()),frameConsumer);
	}
	
	public static void streamConsumer(HttpURLConnection connection,List<Integer> codes, Consumer<String> frameConsumer) {
    	int code;
		try {
			code = connection.getResponseCode();
		} catch (IOException e) {
			throw new ApplicationException(e);
		}
		if(!codes.contains(code)) {
			throw new ApplicationException("模型响应异常:"+code);
		}
		try {
	        int len = 0;
	        char[] res = new char[2048];
			InputStreamReader isr = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8);
	        while ((len = isr.read(res)) != -1) {
	        	String content=new String(res,0,len);
	        	frameConsumer.accept(content);
	        }
		} catch (IOException e) {
			throw new ApplicationException(e);
		}
	}
	
}
